package com.offcn.seckill.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.offcn.seckill.dao.SeckillGoodsMapper;
import com.offcn.seckill.pojo.SeckillGoods;
import com.offcn.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class SeckillGoodsTask {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Scheduled(cron = "0/20 * * * * ?")
    public void loadGoodsToRedis() {
        System.out.println("定时任务执行了");

        //吧数据压入
        //1： 获取时间段集合
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date startTime : dateMenus) {
            //提取开始时间 转化为年月日格式的字符串
            String exDate = DateUtil.date2Str(startTime);

            //创建查询条件
            LambdaQueryWrapper<SeckillGoods> wrapper = new LambdaQueryWrapper<>();

            //审核状态为 1
            wrapper.eq(SeckillGoods::getStatus, "1");

            //库存要大于0
            wrapper.gt(SeckillGoods::getStockCount, 0);

            //开始时间要小于当前时间
            wrapper.ge(SeckillGoods::getStartTime, DateUtil.date2StrFull(startTime));

            //结束时间要  小于开始时间 + 2 小时
            wrapper.lt(SeckillGoods::getEndTime, DateUtil.date2StrFull(DateUtil.addDateHour(startTime, 2)));

            //读取redis中的秒杀商品
            Set keys = redisTemplate.boundHashOps("SeckillGoods_" + exDate).keys();

            //表示已经参加秒杀的商品 不能在进行 添加
            if (keys != null && keys.size() > 0) {
                wrapper.notIn(SeckillGoods::getId, keys);
            }

            //查询数据库   查询 符合参与秒杀的商品
            List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(wrapper);

            for (SeckillGoods seckillGoods : seckillGoodsList) {
                redisTemplate.boundHashOps("SeckillGoods_" + exDate).put(seckillGoods.getId(), seckillGoods);

                Long[] ids = this.pushIds(seckillGoods.getStockCount(), seckillGoods.getGoodsId());

                redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillGoods.getId()).leftPush(ids);
                //设置redis 中的商品的过期时间为2小时
                redisTemplate.expireAt("SeckillGoods_" + exDate, DateUtil.addDateHour(startTime, 2));
            }

        }
    }


    public Long[] pushIds(int len, Long id) {
        Long[] ids = new Long[len];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = id;
        }
        return ids;
    }
}
